package com.hzsparrow.ai.config;

import com.hzsparrow.ai.entity.User;
import com.hzsparrow.ai.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 数据初始化器：在应用启动时初始化必要的数据
 */
@Component
public class DataInitializer implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(DataInitializer.class);

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) throws Exception {
        initAdminUser();
    }

    /**
     * 初始化管理员账户
     */
    private void initAdminUser() {
        try {
            // 检查是否已存在admin用户
            User existingAdmin = userService.getUserByUsername("admin");
            if (existingAdmin != null) {
                logger.info("管理员账户已存在，无需创建");
                return;
            }
            
            // 创建管理员用户
            User adminUser = new User();
            adminUser.setUsername("admin");
            adminUser.setPassword("admin"); // 将在UserService.createUser中加密
            adminUser.setNickname("管理员");
            adminUser.setEmail("admin@example.com");
            adminUser.setRole("ROLE_ADMIN");
            adminUser.setEnabled(true);
            
            userService.createUser(adminUser);
            logger.info("管理员账户创建成功");
        } catch (Exception e) {
            logger.error("初始化管理员账户失败：", e);
        }
    }
} 